<?php
	class User extends Controller{

		/*
		 * This basically inherits the Controller parent
		 */
		function User(){
			parent::Controller();	
		}

		/*
		 * This is loaded by default when a user sign in his her account. 
		 */
		function index(){	
			$data['id'] = $this->session->userdata('id');
			$date = explode("-", date("Y-m-d"));
			$data['year'] = $date[0];
			$data['month'] = $date[1];
			
			$surveys = $this->User_model->getImportantDates($data['id'], $data['year'], $data['month']);
			
			$mark = array();
			$today = $date[2];
			$events = array();
			for($i = 1; $i <= 31; $i++)
			{
				$events[$i] = array();
				foreach($surveys as $survey)
				{
					$begin_day = explode("-", $survey['begin_date']);
					$day_created = explode("-", $survey['date_created']);
					$end_day = explode("-", $survey['end_date']);				
					
					if($i == $day_created[2] && $date[0] == $day_created[0] && $date[1] == $day_created[1])
					{
						if(!array_key_exists($i, $mark))
						{
							$mark[$i] = "";
						}
						$events[$i][] = $survey['title']." was created";
					}
					
					if($i == $begin_day[2] && $date[0] == $begin_day[0] && $date[1] == $begin_day[1])
					{
						if(!array_key_exists($i, $mark))
						{
							$mark[$i] = "";
						}
						if($i < $today)
						{
							$events[$i][] = $survey['title']." began";
						}
						
						else if ($i == $today)
						{
							$events[$i][] = $survey['title']." begins";
						}
						
						else
						{
							$events[$i][] = $survey['title']." will begin";
						}
					}
					
					if($i == $end_day[2] && $date[0] == $end_day[0] && $date[1] == $end_day[1])
					{
						if(!array_key_exists($i, $mark))
						{
							$mark[$i] = "";
						}
						if($i < $today)
						{
							$events[$i][] = $survey['title']." ended";
						}
						
						else
						{
							$events[$i][] = $survey['title']." will end";
						}
					}
				}	
			}
			$user_id = $data['id'];
			$sql = "SELECT profile_pic FROM user
					WHERE user_id = $user_id";
			$result = $this->db->query($sql);
			$data['profile_pic'] = $result->row()->profile_pic;
			
			$data['mark'] = $mark;	
			$data['events'] = $events;
			$gate['body'] = $this->load->view('user/user_home', $data, TRUE);
			$this->load->view('main',$gate);
		}

		/*
			Searches for surveys whose title matches the whole or part of the key given by the user.
		*/
		function search_survey(){
			$user_id = $this->session->userdata('id');
			$toSearch = $_POST['search'];
			
			$super =  $this->uri->segment(3);//get the 3rd uri segment to check privilege
			if ($super == FALSE){//this means that it is a normal user

			
			$data['id'] = $this->session->userdata('id');
			$data['surveys'] = $this->User_model->search_survey($user_id,$toSearch);
			
			}
			else{ // if a segment exists, it is a subuser.
				$data['id'] = $super;
				$data['surveys'] = $this->User_model->search_survey($super,$toSearch);
			
			}
			$data['search'] = true;
			$data['super'] = $super;
			$gate['body'] = $this->load->view('user/survey_options',$data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
			Views all the survey that was created by the user.
		*/
		function view_survey(){
			$this->load->model('User_model');
			//query
			$super =  $this->uri->segment(3);
			if ($super == FALSE){// test for privileges

			//normal
			$data['id'] = $this->session->userdata('id');
			$surveys = $this->User_model->get_my_surveys($data['id']); //user id to
			
			
			}
			else{ // subsuer
				$data['id'] = $super;
				$surveys = $this->User_model->get_my_surveys($super);
			}
			$data['super'] = $super;
			$data['surveys'] = $surveys;
			$gate['body'] = $this->load->view('user/survey_options',$data, TRUE);
			$this->load->view('main', $gate);

		}
		
		/*
		 * Accesses all categories, questions, choices, and answers of a survey to be passed
		 * to the view_text_report.php
		 *
		 * Parameter:
		 * $id -> the user id of the current logged in user
		 * $survey_id -> survey that needs to generate the text report
		 */
		function view_survey_report($id,$survey_id)
		{
			//gets the user id from the session data
			$user_id = $this->session->userdata('id');
			//gets the survey title
			$title = $this->User_model->get_survey_title($survey_id);
			//checks if current survey has question_groups
			$has_groups = $this->User_model->has_groups($survey_id);
			
			//initializations
			$categories = array();
			$question = array();
			$narrative = array();
			$text_label = array();
			$choice = array();
			$answer = array();
			
			//gets all categories, questions, choices, and answers for a survey with categories
			if ($has_groups)
			{
				//gets the all categories defined for a survey
				$temp5 = $this->User_model->get_categories($survey_id);
				for ($n = 0; $n < $temp5->num_rows; $n++)
				{
					$categories[$n] = $temp5->row($n);
					
					//gets all questions defined in a category
					$temp = $this->User_model->get_questions_grouped($survey_id,$categories[$n]->category_id,$categories[$n]->category_name);
					
					for ($i = 0; $i < $temp->num_rows; $i++)
					{
						$question[$n][$i] = $temp->row($i);
						
						//if question is text or a paragraph text
						if(($question[$n][$i]->type == 'paragraph text') || ($question[$n][$i]->type == 'text')) 
						{
							//there is no choices
							$choice[$n][$i][0] = null;
							
							//get all answers
							$temp3 = $this->User_model->get_text_answers($survey_id, $question[$n][$i]->question_number);
							for ($k = 0; $k < $temp3->num_rows; $k++)
							{
								$answer[$n][$i][$k] = $temp3->row($k)->body;
							}
							if ($temp3->num_rows == 0) {
								$answer[$n][$i][0] = null;
							}
						//if question is multiple choice, check box or choose
						}else if (($question[$n][$i]->type == 'multiple choice') || ($question[$n][$i]->type == 'checkboxes') || ($question[$n][$i]->type == 'choose'))
						{
							//get choices available
							$temp2 = $this->User_model->get_choices($survey_id, $question[$n][$i]->question_number);
							for($j = 0; $j < $temp2->num_rows; $j++)
							{
								//count the number of answers corresponding to a choice
								$choice[$n][$i][$j] = $temp2->row($j)->body;
								$answer[$n][$i][$j] = $this->User_model->count_answer($survey_id, $question[$n][$i]->question_number, $choice[$n][$i][$j]);						
							}
						//if question is scale
						}else if ($question[$n][$i]->type == 'scale')
						{
							//get choices available
							$temp4 = $this->User_model->get_choices($survey_id, $question[$n][$i]->question_number);
							
							//answers for scale are stored as 1, 2, 3, 4, 5
							for ($l = 0; $l < 5; $l++)
							{
								$m = $l + 1;
								if ($l == 0) {
									$choice[$n][$i][$l] = $temp4->row(0)->body;
								}else if ($l == 4) {
									$choice[$n][$i][$l] = $temp4->row(1)->body;
								}else {
									$choice[$n][$i][$l] = $m;
								}
								//count the number of answers corresponding to a choice
								$answer[$n][$i][$l] = $this->User_model->count_answer($survey_id, $question[$n][$i]->question_number, $m);
							}
						//if question is ranking
						}else if ($question[$n][$i]->type == 'ranking')
						{
							//get choices available
							$temp6 = $this->User_model->get_choices($survey_id, $question[$n][$i]->question_number);
							$ranks = $temp6->num_rows;
							$x = 0;
							foreach($temp6->result() as $rank_options)
							{
								$sum = 0;
								$number = 0;
								for($y = 1; $y <= $ranks; $y++)
								{
									//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
									$clause = $y. " " . $rank_options->body;
									
									//count the number of answers corresponding to a choice
									$ctr_answer = $this->User_model->count_answer($survey_id, $question[$n][$i]->question_number, $clause);
									$number = $number + $ctr_answer;
									$sum = $sum + ($y*$ctr_answer);
								}
								//get the average rank for a choice
								if ($number == 0)
								{
									$answer[$n][$i][$x] = 0;
								}else {
									$answer[$n][$i][$x] = $sum / $number;
								}
								$choice[$n][$i][$x] = $rank_options->body;
								$x++;

							}
						}
						//get the answers for a question
						$list = $this->User_model->get_answers($survey_id, $question[$n][$i]->question_number);
						$q = 0;
						//access the answers for follow up questions if there is any
						foreach($list->result() as $exp)
						{
							$narrative[$n][$i][$q] = $exp->explanation;
							$q++;
						}
						if ($list->num_rows == 0)
						{
							$narrative[$n][$i][0] = null;
						}
						//access the follow up question if there is any
						$text_label[$n][$i] = $question[$n][$i]->text_label;
					}
				}
			//gets all questions, choices, and answers for a survey without categories
			}else {
				//gets all questions available in a survey
				$temp = $this->User_model->get_questions($survey_id);
				
				for ($i = 0; $i < $temp->num_rows; $i++)
				{
					$question[$i] = $temp->row($i);
					//if question is text or a paragraph text
					if(($question[$i]->type == 'paragraph text') || ($question[$i]->type == 'text')) 
					{
						//there is no choices
						$choice[$i][0] = null;
						
						//get all answers
						$temp3 = $this->User_model->get_text_answers($survey_id, $question[$i]->question_number);						
						for ($k = 0; $k < $temp3->num_rows; $k++)
						{
							$answer[$i][$k] = $temp3->row($k)->body;
						}
						if ($temp3->num_rows == 0) {
							$answer[$i][0] = null;
						}
					//if question is multiple choice, check box or choose
					}else if (($question[$i]->type == 'multiple choice') || ($question[$i]->type == 'checkboxes') || ($question[$i]->type == 'choose'))
					{
						//get choices available
						$temp2 = $this->User_model->get_choices($survey_id, $question[$i]->question_number);						
						for($j = 0; $j < $temp2->num_rows; $j++)
						{
							//count the number of answers corresponding to a choice
							$choice[$i][$j] = $temp2->row($j)->body;
							$answer[$i][$j] = $this->User_model->count_answer($survey_id, $question[$i]->question_number, $choice[$i][$j]);						
						}
					//if question is scale
					}else if ($question[$i]->type == 'scale')
					{
						//get choices available
						$temp4 = $this->User_model->get_choices($survey_id, $question[$i]->question_number);
						
						//answers for scale are stored as 1, 2, 3, 4, 5
						for ($l = 0; $l < 5; $l++)
						{
							$m = $l + 1;
							if ($l == 0) {
								$choice[$i][$l] = $temp4->row(0)->body;
							}else if ($l == 4) {
								$choice[$i][$l] = $temp4->row(1)->body;
							}else {
								$choice[$i][$l] = $m;
							}
							//count the number of answers corresponding to a choice
							$answer[$i][$l] = $this->User_model->count_answer($survey_id, $question[$i]->question_number, $m);
						}
					//if question is ranking
					}else if ($question[$i]->type == 'ranking')
					{
						//get choices available
						$temp6 = $this->User_model->get_choices($survey_id, $question[$i]->question_number);
						$ranks = $temp6->num_rows;
						$x = 0;
						foreach($temp6->result() as $rank_options)
						{
							$sum = 0;
							$number = 0;
							for($y = 1; $y <= $ranks; $y++)
							{
								//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
								$clause = $y. " " . $rank_options->body;
								
								//count the number of answers corresponding to a choice
								$ctr_answer = $this->User_model->count_answer($survey_id, $question[$i]->question_number, $clause);
								$number = $number + $ctr_answer;
								$sum = $sum + ($y*$ctr_answer);
							}
							//get the average rank for a choice
							if($number == 0)
							{
								$answer[$i][$x] = 0;
							}else {
								$answer[$i][$x] = $sum / $number;
							}
							$choice[$i][$x] = $rank_options->body;
							$x++;
						}
					}
					//get the answers for a question
					$list = $this->User_model->get_answers($survey_id, $question[$i]->question_number);
					$q = 0;
					//access the answers for follow up questions if there is any
					foreach($list->result() as $exp)
					{
						$narrative[$i][$q] = $exp->explanation;
						$q++;
					}
					if ($list->num_rows == 0)
					{
						$narrative[$i][0] = null;
					}
					//access the follow up question if there is any
					$text_label[$i] = $question[$i]->text_label;
				}
			}
			
			//set up the $data array which would contain all that needs to be passed
			$data['has_groups'] = $has_groups;
			$data['gender_required'] = $this->User_model->is_gender_required($survey_id);
			$data['age_required'] = $this->User_model->is_age_required($survey_id);
			$data['category'] = $categories;
			$data['num_invitations'] = $this->User_model->number_invitations($survey_id);
			$data['num_respondents'] = $this->User_model->number_respondents_answered($survey_id);
			$data['questions'] = $question;
			$data['choice'] = $choice;
			$data['answer'] = $answer;
			$data['id'] = $user_id;
			$data['survey_id'] = $survey_id;
			$data['narrative'] = $narrative;
			$data['text_label'] = $text_label;
			$data['title'] = $title;
			
			//go to view_text_report.php
			$gate['body'] = $this->load->view('user/view_text_report',$data, TRUE);
			$this->load->view('main', $gate);
		}
		
		/*
		 * Generates graphs for the report and passes the filepath
		 * to the view_report.php
		 *
		 * Parameter:
		 * $id -> the user id of the current logged in user
		 * $survey_id -> survey that needs to generate the text report 
		 */
		function view_survey_graph($id,$survey_id)
		{
			//gets the user id from the session data
			$user_id = $this->session->userdata('id');
			//gets the input passed from the view_text_report.php
			$chart_type = $_POST['chart'];
			$separator = $_POST['separator'];
			//get the survey title
			$title = $this->User_model->get_survey_title($survey_id);
			//checks if current survey has question groups
			$has_groups = $this->User_model->has_groups($survey_id);
			
			//initialization
			$categories = array();
			
			//defined groups when separated by age
			//teens = < 18 years old
			//middle age = 18 - 30 years old
			//adult = 31 - 59 years old
			//senior = > 59 years old
			$teen_upper = date('Y-m-d');
			$teen_lower = date('Y') - 18 . "-" . date('m-d');
			$middle_upper = date('Y') - 18 . "-" . date('m-d');
			$middle_lower = date('Y') - 31 . "-" . date('m-d');
			$adult_upper = date('Y') - 31 . "-" . date('m-d');
			$adult_lower = date('Y') - 60 . "-" . date('m-d');
			$senior_upper = date('Y') - 60 . "-" . date('m-d');
			$senior_lower = date('Y') - 1000 . "-" . date('m-d');
			
			//generates graphs for survey with categories
			if($has_groups) 
			{
				//gets the all categories defined for a survey
				$categories = $this->User_model->get_categories($survey_id);
				$no_groups = 0;
				
				foreach($categories->result() as $qcat)
				{
					//resets the values contained in the following arrays
					//$graphs will hold graphs generated for each question, $height refers to the height of corresponding graphs
					unset($graphs);
					unset($height);
					//gets all questions defined in a category
					$questions = $this->User_model->get_questions_grouped($survey_id, $qcat->category_id, $qcat->category_name);
					$i = 0;
					foreach($questions->result() as $row)
					{
						//resets the values contained in the following arrays
						//$labels will hold labels for graphs, $templabels is for temporary storage
						unset($labels);
						unset($templabels);
						//$answers will hold data needed in graphs, $temp is for temporary storage
						unset($answers);
						unset($temp);
						//similar to above but holds data when separated by gender
						unset($temp_m);
						unset($temp_f);
						unset($answers_m);
						unset($answers_f);
						//similar to above but holds data when separated by age
						unset($temp_teen);
						unset($temp_middle);
						unset($temp_adult);
						unset($temp_senior);
						unset($answers_teen);
						unset($answers_middle);
						unset($answers_adult);
						unset($answers_senior);
						
						//if question is multiple choice, check box or choose
						if(($row->type == 'multiple choice') || ($row->type == 'checkboxes') || ($row->type == 'choose'))
						{
							//get choices available
							$choices = $this->User_model->get_choices($survey_id,$row->question_number);
							$j=0;
							foreach($choices->result() as $row2)
							{
								if ($separator == 'none')
								{
									//count the number of answers corresponding to a choice
									$temp[$j] = $this->User_model->count_answer($survey_id, $row->question_number, $row2->body);
									$templabels[$j] = $row2->body;
									$j++;
								}else if ($separator == 'gender')
								{
									//count the number of answers corresponding to a choice separated by gender
									$temp_m[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $row2->body, 'M');
									$temp_f[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $row2->body, 'F');
									$templabels[$j] = $row2->body;
									$j++;
								}else if ($separator == 'age')
								{									
									//count the number of answers corresponding to a choice separated by age
									$temp_teen[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $teen_upper, $teen_lower);
									$temp_middle[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $middle_upper, $middle_lower);
									$temp_adult[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $adult_upper, $adult_lower);
									$temp_senior[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $senior_upper, $senior_lower);
									$templabels[$j] = $row2->body;
									$j++;
								}
							}
						//if question is scale							
						}else if($row->type == 'scale')
						{
							//get choices available
							$choices = $this->User_model->get_choices($survey_id,$row->question_number);
							for($j = 0; $j < 5; $j++)
							{
								$k = $j + 1;
								//answers for scale are stored as 1, 2, 3, 4, 5
								if ($separator == 'none')
								{
									//count the number of answers corresponding to a choice
									$temp[$j] = $this->User_model->count_answer($survey_id, $row->question_number, $k);

									if($j == 0){
										$templabels[$j] = $choices->row(0)->body . " ". $k;
									}
									else if ($j == 4) {
										$templabels[$j] = $choices->row(1)->body . " ". $k;
									}
									else {
										$templabels[$j] = $k;
									}
								}else if ($separator == 'gender')
								{
									//count the number of answers corresponding to a choice separated by gender
									$temp_m[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $k, 'M');
									$temp_f[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $k, 'F');
									if($j == 0){
										$templabels[$j] = $choices->row(0)->body . " ". $k;
									}
									else if ($j == 4) {
										$templabels[$j] = $choices->row(1)->body . " ". $k;
									}
									else {
										$templabels[$j] = $k;
									}
								}else if ($separator == 'age')
								{
									//count the number of answers corresponding to a choice separated by age
									$temp_teen[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $teen_upper, $teen_lower);
									$temp_middle[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $middle_upper, $middle_lower);
									$temp_adult[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $adult_upper, $adult_lower);
									$temp_senior[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $senior_upper, $senior_lower);
									
									if($j == 0){
										$templabels[$j] = $choices->row(0)->body . " ". $k;
									}
									else if ($j == 4) {
										$templabels[$j] = $choices->row(1)->body . " ". $k;
									}
									else {
										$templabels[$j] = $k;
									}
								}
							}
						//if question is ranking
						}else if ($row->type == 'ranking')
						{
							//get choices available
							$temp6 = $this->User_model->get_choices($survey_id, $row->question_number);
							$ranks = $temp6->num_rows;
							$x = 0;
							foreach($temp6->result() as $rank_options)
							{
								if ($separator == 'none')
								{
									$sum = 0;
									$number = 0;
									for($y = 1; $y <= $ranks; $y++)
									{
										//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
										$clause = $y. " " . $rank_options->body;
										//count the number of answers corresponding to a choice
										$ctr_answer = $this->User_model->count_answer($survey_id, $row->question_number, $clause);
										$number = $number + $ctr_answer;
										$sum = $sum + ($y*$ctr_answer);								
									}
									//get the average rank for a choice
									if ($number == 0)
									{
										$temp[$x] = 0;
									}else {
										$temp[$x] = $sum / $number;
									}
									$templabels[$x] = $rank_options->body;
								}else if ($separator == 'gender')
								{
									$sum_m = 0;
									$number_m = 0;
									$sum_f = 0;
									$number_f = 0;
									
									for($y = 1; $y <= $ranks; $y++)
									{
										//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
										$clause = $y. " " . $rank_options->body;
										//count the number of answers corresponding to a choice separated by gender
										$ctr_answer_m = $this->User_model->count_answer_gender($survey_id, $row->question_number, $clause, 'M');
										$number_m = $number_m + $ctr_answer_m;
										$sum_m = $sum_m + ($y*$ctr_answer_m);

										$ctr_answer_f = $this->User_model->count_answer_gender($survey_id, $row->question_number, $clause, 'F');
										$number_f = $number_f + $ctr_answer_f;
										$sum_f = $sum_f + ($y*$ctr_answer_f);
									}
									//get the average rank for a choice
									if ($number_m == 0)
									{
										$temp_m[$x] = 0;
									}else {
										$temp_m[$x] = $sum_m / $number_m;
									}
									if ($number_f == 0)
									{
										$temp_f[$x] = 0;
									}else {
										$temp_f[$x] = $sum_f / $number_f;
									}
									$templabels[$x] = $rank_options->body;
								}else if ($separator == 'age')
								{
									$sum_teen = 0;
									$number_teen = 0;
									$sum_middle = 0;
									$number_middle = 0;
									$sum_adult = 0;
									$number_adult = 0;
									$sum_senior = 0;
									$number_senior = 0;
									for($y = 1; $y <= $ranks; $y++)
									{
										//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
										$clause = $y. " " . $rank_options->body;
										//count the number of answers corresponding to a choice separated by age
										$ctr_answer_teen = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $teen_upper, $teen_lower);
										$number_teen = $number_teen + $ctr_answer_teen;
										$sum_teen = $sum_teen + ($y*$ctr_answer_teen);

										$ctr_answer_middle = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $middle_upper, $middle_lower);
										$number_middle = $number_middle + $ctr_answer_middle;
										$sum_middle = $sum_middle + ($y*$ctr_answer_middle);
										
										$ctr_answer_adult = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $adult_upper, $adult_lower);
										$number_adult = $number_adult + $ctr_answer_adult;
										$sum_adult = $sum_adult + ($y*$ctr_answer_adult);
										
										$ctr_answer_senior = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $senior_upper, $senior_lower);
										$number_senior = $number_senior + $ctr_answer_senior;
										$sum_senior = $sum_senior + ($y*$ctr_answer_senior);
									}
									//get the average rank for a choice
									if ($number_teen == 0)
									{
										$temp_teen[$x] = 0;
									}else {
										$temp_teen[$x] = $sum_teen / $number_teen;
									}
									
									if ($number_middle == 0)
									{
										$temp_middle[$x] = 0;
									}else {
										$temp_middle[$x] = $sum_middle / $number_middle;
									}
									
									if ($number_adult == 0)
									{
										$temp_adult[$x] = 0;
									}else {
										$temp_adult[$x] = $sum_adult / $number_adult;
									}
									
									if ($number_senior == 0)
									{
										$temp_senior[$x] = 0;
									}else {
										$temp_senior[$x] = $sum_senior / $number_senior;
									}
									
									$templabels[$x] = $rank_options->body;
								}
								$x++;
							}							
						}
						if( ($row->type == 'text') || ($row->type == 'paragraph text'))
						{
						
						}else
						{
							//creating a bar graph by using the functions defined in jpgraph_pi.php
							if( $chart_type == 'bar') {
								$labels = $templabels;
								//height is determined by number of choices * 50
								if ($separator == 'none')
								{
									$answers = $temp;
									$height[$i] = count($answers) * 50;
									$graphs[$i] = barchart($answers, $row->body, $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
								}else if ($separator === 'gender')
								{
									$answers_m = $temp_m;
									$height[$i] = count($answers_m) * 50;
									$graphs[$i] = barchart($answers_m, $row->body . ": Men's Answers", $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
									
									$answers_f = $temp_f;
									$height[$i] = count($answers_f) * 50;
									$graphs[$i] = barchart($answers_f, $row->body . ": Women's Answers", $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
								}else if ($separator == 'age')
								{
									$answers_teen = $temp_teen;
									$height[$i] = count($answers_teen) * 50;
									$graphs[$i] = barchart($answers_teen, $row->body . ": Teens' Answers (< 18 years old)", $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
										
									$answers_middle = $temp_middle;
									$height[$i] = count($answers_middle) * 50;
									$graphs[$i] = barchart($answers_middle, $row->body . ": Middle age's Answers (18 - 30 years old)", $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
									
									$answers_adult = $temp_adult;
									$height[$i] = count($answers_adult) * 50;
									$graphs[$i] = barchart($answers_adult, $row->body . ": Adults' Answers (31 - 59 years old)", $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
										
									$answers_senior = $temp_senior;
									$height[$i] = count($answers_senior) * 50;
									$graphs[$i] = barchart($answers_senior, $row->body . ": Seniors' Answers (> 59 years old)", $height[$i]);
									$graphs[$i]->xaxis->SetTickLabels($labels);
									$i++;
								}
							}
							//creates a pie graph by using the functions defined in jpgraph_pi.php
							else if( $chart_type == 'pie') 
							{
								//height is fixed to 400
								//no need to pass data for choices with no answers
								$ind = 0;
								if ($separator == 'none')
								{
									for($check = 0; $check < count($temp); $check++)
									{
										if($temp[$check] != 0) 
										{
											$answers[$ind] = $temp[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}									
									}
									if (isset($answers))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers, $row->body, $labels);
										$i++;
									}
								}else if ($separator == 'gender')
								{
									for($check = 0; $check < count($temp_m); $check++)
									{
										if ($temp_m[$check] != 0)
										{
											$answers_m[$ind] = $temp_m[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}
									}
									if (isset($answers_m))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers_m, $row->body. ": Men's Answers", $labels);
										$i++;
									}
									$ind = 0;
									for($check = 0; $check < count($temp_f); $check++)
									{
										if ($temp_f[$check] != 0)
										{
											$answers_f[$ind] = $temp_f[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}
									}
									if (isset($answers_f))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers_f, $row->body. ": Women's Answers", $labels);
										$i++;
									}
								}else if ($separator == 'age')
								{
									for($check = 0; $check < count($temp_teen); $check++)
									{
										if ($temp_teen[$check] != 0)
										{
											$answers_teen[$ind] = $temp_teen[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}
									}
									if (isset($answers_teen))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers_teen, $row->body. ": Teens' Answers (< 18 years old)", $labels);
										$i++;
									}
									$ind = 0;
									for($check = 0; $check < count($temp_middle); $check++)
									{
										if ($temp_middle[$check] != 0)
										{
											$answers_middle[$ind] = $temp_middle[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}
									}
									if (isset($answers_middle))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers_middle, $row->body. ": Middle Age's Answers (18 - 30 years old)", $labels);
										$i++;
									}
									$ind = 0;
									for($check = 0; $check < count($temp_adult); $check++)
									{
										if ($temp_adult[$check] != 0)
										{
											$answers_adult[$ind] = $temp_adult[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}
									}
									if (isset($answers_adult))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers_adult, $row->body. ": Adults' Answers (31 - 59 years old)", $labels);
										$i++;
									}
									$ind = 0;
									for($check = 0; $check < count($temp_senior); $check++)
									{
										if ($temp_senior[$check] != 0)
										{
											$answers_senior[$ind] = $temp_senior[$check];
											$labels[$ind] = $templabels[$check];
											$ind++;
										}
									}
									if (isset($answers_senior))
									{
										$height[$i] = 400;
										$graphs[$i] = piechart($answers_senior, $row->body. ": Seniors' Answers (> 59 years old)", $labels);
										$i++;
									}
								}
							}	
						}
					}
					//combines the graphs generated for a category, and writes it to a file with the format
					//'chart-category-number-surveyid-userid.png' ex. 'chart-category-2-1-1.png' and stores it
					//in the graphs folder located at the root file together with the index.php
					if( (!isset($graphs)) && (!isset($height)))
					{
						$graph_file_name[$no_groups] = null;
					}else
					{
						$graph_file_name[$no_groups] = 'graphs/chart-category'. $no_groups .'-'.$survey_id. '-'. $user_id . '.png';
						$mgraph = combined_graph($graphs, $height);
						
						if (file_exists($graph_file_name[$no_groups]))
						{
							unlink($graph_file_name[$no_groups]);
						}
						$mgraph->Stroke('./'.$graph_file_name[$no_groups]);
					}
					$no_groups++;
				}
			}
			//generates graphs for survey without categories
			else{
				//get all questions defined in a survey
				$questions = $this->User_model->get_questions($survey_id);
				$i = 0;
				foreach($questions->result() as $row)
				{
					//resets the values contained in the following arrays
					//$labels will hold labels for graphs, $templabels is for temporary storage
					unset($labels);
					unset($templabels);
					//$answers will hold data needed in graphs, $temp is for temporary storage
					unset($answers);
					unset($temp);
					//similar to above but holds data when separated by gender
					unset($temp_m);
					unset($temp_f);
					unset($answers_m);
					unset($answers_f);
					//similar to above but holds data when separated by age
					unset($temp_teen);
					unset($temp_middle);
					unset($temp_adult);
					unset($temp_senior);
					unset($answers_teen);
					unset($answers_middle);
					unset($answers_adult);
					unset($answers_senior);
					
					//if question is multiple choice, check box or choose
					if(($row->type == 'multiple choice') || ($row->type == 'checkboxes') || ($row->type == 'choose'))
					{
						//get choices available
						$choices = $this->User_model->get_choices($survey_id,$row->question_number);
						$j=0;
						foreach($choices->result() as $row2)
						{
							if ($separator == 'none')
							{
								//count the number of answers corresponding to a choice
								$temp[$j] = $this->User_model->count_answer($survey_id, $row->question_number, $row2->body);
								$templabels[$j] = $row2->body;
								$j++;
							}else if ($separator == 'gender')
							{
								//count the number of answers corresponding to a choice separated by gender
								$temp_m[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $row2->body, 'M');
								$temp_f[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $row2->body, 'F');
								$templabels[$j] = $row2->body;
								$j++;
							}else if ($separator == 'age')
							{
								//count the number of answers corresponding to a choice separated by age
								$temp_teen[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $teen_upper, $teen_lower);
								$temp_middle[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $middle_upper, $middle_lower);
								$temp_adult[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $adult_upper, $adult_lower);
								$temp_senior[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $row2->body, $senior_upper, $senior_lower);
								$templabels[$j] = $row2->body;
								$j++;
							}
						}
					//if question is scale							
					}else if($row->type == 'scale')
					{
						//get choices available
						$choices = $this->User_model->get_choices($survey_id,$row->question_number);
						for($j = 0; $j < 5; $j++)
						{
							$k = $j + 1;
							//answers for scale are stored as 1, 2, 3, 4, 5
							if ($separator == 'none')
							{
								//count the number of answers corresponding to a choice
								$temp[$j] = $this->User_model->count_answer($survey_id, $row->question_number, $k);
								if($j == 0){
									$templabels[$j] = $choices->row(0)->body . " ". $k;
								}
								else if ($j == 4) {
									$templabels[$j] = $choices->row(1)->body . " ". $k;
								}
								else {
									$templabels[$j] = $k;
								}
							}else if ($separator == 'gender')
							{
								//count the number of answers corresponding to a choice separated by gender
								$temp_m[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $k, 'M');
								$temp_f[$j] = $this->User_model->count_answer_gender($survey_id, $row->question_number, $k, 'F');
								if($j == 0){
									$templabels[$j] = $choices->row(0)->body . " ". $k;
								}
								else if ($j == 4) {
									$templabels[$j] = $choices->row(1)->body . " ". $k;
								}
								else {
									$templabels[$j] = $k;
								}
							}else if ($separator == 'age')
							{
								//count the number of answers corresponding to a choice separated by age
								$temp_teen[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $teen_upper, $teen_lower);
								$temp_middle[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $middle_upper, $middle_lower);
								$temp_adult[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $adult_upper, $adult_lower);
								$temp_senior[$j] = $this->User_model->count_answer_age($survey_id, $row->question_number, $k, $senior_upper, $senior_lower);
								
								if($j == 0){
									$templabels[$j] = $choices->row(0)->body . " ". $k;
								}
								else if ($j == 4) {
									$templabels[$j] = $choices->row(1)->body . " ". $k;
								}
								else {
									$templabels[$j] = $k;
								}
							}
						}
					//if question is ranking
					}else if ($row->type == 'ranking')
					{
						//get choices available
						$temp6 = $this->User_model->get_choices($survey_id, $row->question_number);
						$ranks = $temp6->num_rows;
						$x = 0;
						foreach($temp6->result() as $rank_options)
						{
							if ($separator == 'none')
							{
								$sum = 0;
								$number = 0;
								for($y = 1; $y <= $ranks; $y++)
								{
									//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
									$clause = $y. " " . $rank_options->body;
									//count the number of answers corresponding to a choice
									$ctr_answer = $this->User_model->count_answer($survey_id, $row->question_number, $clause);
									$number = $number + $ctr_answer;
									$sum = $sum + ($y*$ctr_answer);								
								}
								//get the average rank for a choice
								if ($number == 0)
								{
									$temp[$x] = 0;
								}else {
									$temp[$x] = $sum / $number;
								}
								$templabels[$x] = $rank_options->body;
							}else if ($separator == 'gender')
							{
								$sum_m = 0;
								$number_m = 0;
								$sum_f = 0;
								$number_f = 0;
								
								for($y = 1; $y <= $ranks; $y++)
								{
									//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
									$clause = $y. " " . $rank_options->body;
									//count the number of answers corresponding to a choice separated by gender
									$ctr_answer_m = $this->User_model->count_answer_gender($survey_id, $row->question_number, $clause, 'M');
									$number_m = $number_m + $ctr_answer_m;
									$sum_m = $sum_m + ($y*$ctr_answer_m);

									$ctr_answer_f = $this->User_model->count_answer_gender($survey_id, $row->question_number, $clause, 'F');
									$number_f = $number_f + $ctr_answer_f;
									$sum_f = $sum_f + ($y*$ctr_answer_f);
								}
								//get the average rank for a choice
								if ($number_m == 0)
								{
									$temp_m[$x] = 0;
								}else {
									$temp_m[$x] = $sum_m / $number_m;
								}
								if ($number_f == 0)
								{
									$temp_f[$x] = 0;
								}else {
									$temp_f[$x] = $sum_f / $number_f;
								}
								$templabels[$x] = $rank_options->body;
							}else if ($separator == 'age')
							{
								$sum_teen = 0;
								$number_teen = 0;
								$sum_middle = 0;
								$number_middle = 0;
								$sum_adult = 0;
								$number_adult = 0;
								$sum_senior = 0;
								$number_senior = 0;
								for($y = 1; $y <= $ranks; $y++)
								{
									//answers for ranking are stored as 'rankNumber Choice' ex. 1 cs192
									$clause = $y. " " . $rank_options->body;
									//count the number of answers corresponding to a choice separated by age
									$ctr_answer_teen = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $teen_upper, $teen_lower);
									$number_teen = $number_teen + $ctr_answer_teen;
									$sum_teen = $sum_teen + ($y*$ctr_answer_teen);

									$ctr_answer_middle = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $middle_upper, $middle_lower);
									$number_middle = $number_middle + $ctr_answer_middle;
									$sum_middle = $sum_middle + ($y*$ctr_answer_middle);
									
									$ctr_answer_adult = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $adult_upper, $adult_lower);
									$number_adult = $number_adult + $ctr_answer_adult;
									$sum_adult = $sum_adult + ($y*$ctr_answer_adult);
									
									$ctr_answer_senior = $this->User_model->count_answer_age($survey_id, $row->question_number, $clause, $senior_upper, $senior_lower);
									$number_senior = $number_senior + $ctr_answer_senior;
									$sum_senior = $sum_senior + ($y*$ctr_answer_senior);
								}
								//get the average rank for a choice
								if ($number_teen == 0)
								{
									$temp_teen[$x] = 0;
								}else {
									$temp_teen[$x] = $sum_teen / $number_teen;
								}
								
								if ($number_middle == 0)
								{
									$temp_middle[$x] = 0;
								}else {
									$temp_middle[$x] = $sum_middle / $number_middle;
								}
								
								if ($number_adult == 0)
								{
									$temp_adult[$x] = 0;
								}else {
									$temp_adult[$x] = $sum_adult / $number_adult;
								}
								
								if ($number_senior == 0)
								{
									$temp_senior[$x] = 0;
								}else {
									$temp_senior[$x] = $sum_senior / $number_senior;
								}
								
								$templabels[$x] = $rank_options->body;
							}
							$x++;
						}							
					}
					
					if( ($row->type == 'text') || ($row->type == 'paragraph text'))
					{
					
					}else
					{
						//creating a bar graph by using the functions defined in jpgraph_pi.php
						if( $chart_type == 'bar') {
							$labels = $templabels;
							//height is determined by number of choices * 50
							if ($separator == 'none')
							{
								$answers = $temp;
								$height[$i] = count($answers) * 50;
								$graphs[$i] = barchart($answers, $row->body, $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
							}else if ($separator === 'gender')
							{
								$answers_m = $temp_m;
								$height[$i] = count($answers_m) * 50;
								$graphs[$i] = barchart($answers_m, $row->body . ": Men's Answers", $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
								
								$answers_f = $temp_f;
								$height[$i] = count($answers_f) * 50;
								$graphs[$i] = barchart($answers_f, $row->body . ": Women's Answers", $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
							}else if ($separator == 'age')
							{
								$answers_teen = $temp_teen;
								$height[$i] = count($answers_teen) * 50;
								$graphs[$i] = barchart($answers_teen, $row->body . ": Teens' Answers (< 18 years old)", $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
									
								$answers_middle = $temp_middle;
								$height[$i] = count($answers_middle) * 50;
								$graphs[$i] = barchart($answers_middle, $row->body . ": Middle age's Answers (18 - 30 years old)", $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
								
								$answers_adult = $temp_adult;
								$height[$i] = count($answers_adult) * 50;
								$graphs[$i] = barchart($answers_adult, $row->body . ": Adults' Answers (31 - 59 years old)", $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
									
								$answers_senior = $temp_senior;
								$height[$i] = count($answers_senior) * 50;
								$graphs[$i] = barchart($answers_senior, $row->body . ": Seniors' Answers (> 59 years old)", $height[$i]);
								$graphs[$i]->xaxis->SetTickLabels($labels);
								$i++;
							}
						}
						//creating a pie graph by using the functions defined in jpgraph_pi.php
						else if( $chart_type == 'pie') 
						{
							//height is fixed to 400
							//no need to pass data for choices with no answers
							$ind = 0;
							if ($separator == 'none')
							{
								for($check = 0; $check < count($temp); $check++)
								{
									if($temp[$check] != 0) 
									{
										$answers[$ind] = $temp[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}									
								}
								if (isset($answers))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers, $row->body, $labels);
									$i++;
								}
							}else if ($separator == 'gender')
							{
								for($check = 0; $check < count($temp_m); $check++)
								{
									if ($temp_m[$check] != 0)
									{
										$answers_m[$ind] = $temp_m[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}
								}
								if (isset($answers_m))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers_m, $row->body. ": Men's Answers", $labels);
									$i++;
								}
								$ind = 0;
								for($check = 0; $check < count($temp_f); $check++)
								{
									if ($temp_f[$check] != 0)
									{
										$answers_f[$ind] = $temp_f[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}
								}
								if (isset($answers_f))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers_f, $row->body. ": Women's Answers", $labels);
									$i++;
								}
							}else if ($separator == 'age')
							{
								for($check = 0; $check < count($temp_teen); $check++)
								{
									if ($temp_teen[$check] != 0)
									{
										$answers_teen[$ind] = $temp_teen[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}
								}
								if (isset($answers_teen))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers_teen, $row->body. ": Teens' Answers (< 18 years old)", $labels);
									$i++;
								}
								$ind = 0;
								for($check = 0; $check < count($temp_middle); $check++)
								{
									if ($temp_middle[$check] != 0)
									{
										$answers_middle[$ind] = $temp_middle[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}
								}
								if (isset($answers_middle))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers_middle, $row->body. ": Middle Age's Answers (18 - 30 years old)", $labels);
									$i++;
								}
								$ind = 0;
								for($check = 0; $check < count($temp_adult); $check++)
								{
									if ($temp_adult[$check] != 0)
									{
										$answers_adult[$ind] = $temp_adult[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}
								}
								if (isset($answers_adult))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers_adult, $row->body. ": Adults' Answers (31 - 59 years old)", $labels);
									$i++;
								}
								$ind = 0;
								for($check = 0; $check < count($temp_senior); $check++)
								{
									if ($temp_senior[$check] != 0)
									{
										$answers_senior[$ind] = $temp_senior[$check];
										$labels[$ind] = $templabels[$check];
										$ind++;
									}
								}
								if (isset($answers_senior))
								{
									$height[$i] = 400;
									$graphs[$i] = piechart($answers_senior, $row->body. ": Seniors' Answers (> 59 years old)", $labels);
									$i++;
								}
							}
						}	
					}
				}
				//combines the graphs generated for the survey, and writes it to a file with the format
				//'chart-surveyid-userid.png' ex. 'chart-1-1.png' and stores it
				//in the graphs folder located at the root file together with the index.php
				if( (!isset($graphs)) && (!isset($height)))
				{
					$graph_file_name = null;
				}else
				{
					$graph_file_name = 'graphs/chart-'.$survey_id. '-'. $user_id . '.png';
					$mgraph = combined_graph($graphs, $height);
					
					if (file_exists($graph_file_name))
					{
						unlink($graph_file_name);
					}
					$mgraph->Stroke('./'.$graph_file_name);
				}
			}
			
			//set up the $data array which would contain all that needs to be passed
			$data = array();
			$data['survey_id'] = $survey_id;
			$data['graph'] = $graph_file_name;
			$data['has_groups'] = $has_groups;
			$data['category'] = $categories;
			$data['id'] = $user_id;
			$data['title'] = $this->User_model->get_survey_title($survey_id);
			
			//go to view_report.php
			$gate['body'] = $this->load->view('user/view_report',$data, TRUE);
			$this->load->view('main', $gate);
		}

		/*	
			Inserts the question that was created by user to the database
		*/
		function insert_question($survey_id){
						
			$user_id = $this->session->userdata('id');
			//get the next question number
			$next_question_num = $this->User_model->get_number_of_questions($survey_id)+1;
			$toInsert['survey_id'] = $survey_id;
			$toInsert['question_number'] = $next_question_num;
			$toInsert['body'] = $_POST['question'];
			$toInsert['type'] = $_POST['type'];
			$toInsert['text_label'] = $_POST['text_label'];
			if($_POST['type'] == "text"){
				$toInsert['text_label'] = $_POST['text_label2'];
			}
			else{
				$toInsert['text_label'] = $_POST['text_label'];
			}
			$toInsert['null_field'] = ($_POST['null'] == "on" ? FALSE : TRUE);
			
			if(array_key_exists("groups",$_POST)){//check if there is a category
				$toInsert['category_name'] = $_POST['groups'];
			}
			else{
				$toInsert['category_name'] = "";
			}
			
			if (!isset($_POST['with_text'])){
				$toInsert['with_text'] = 0;
			}
			else{
				$toInsert['with_text'] = $_POST['with_text'];
				$toInsert['required'] = $_POST['required'];
			}
			
			if ($_POST['type'] == 'text'){
				$toInsert['required'] = $_POST['required'];
			}
			
			if ($_POST['type'] == 'checkboxes'){
				$toInsert['choice_limit'] = $_POST['choice_limit'];
			}
			
			$this->User_model->insert_questions_data($toInsert);
			
			//insert choices if any
			if (array_key_exists('choice_value',$_POST)){
				$limit =  $_POST['choice_value'];
				for($i = 1; $i <=$limit; $i++){
					$key = "choice".$i;
					$choice = $_POST[$key];
					$new['survey_number'] = $survey_id;
					$new['question_number'] = $next_question_num;
					$new['choice_number'] = $i;
					$new['body'] = $choice;
					
					$this->User_model->insert_choice($new);
				}				
			}
			else{}
			

			
			//redirect to viewing the survey
			$this->view_certain_survey($user_id, $survey_id);
		}

		/*
			loads all the survey created by the user so that he/she can choose which one to edit
		*/
		function edit_survey(){
		
			$data['id'] = $this->session->userdata('id');
			//gets from the database all the surveys tha was created by the user.
			$surveys = $this->User_model->get_my_surveys($data['id']); //user id to
			$data['surveys'] = $surveys;
			$gate['body'] = $this->load->view('user/edit_survey',$data, TRUE);
			$this->load->view('main', $gate);

		}

		/*
			allows a user to add questions this shows the form where the user can enter necessary details
			about the question he/she wants to add
			Parameter:
				$survey_id - necessary to know which survey the question will be added
		*/
		function add_question($survey_id){
			$data = array();
			$data['survey_id'] = $survey_id;
			//test if there if someone has already answered the survey.
			$answers = $this->User_model->count_answer_check($survey_id);
			$data['id'] = $this->session->userdata('id');
			if ($answers == 0){ // you can still add if no one has answered yet.

				
				$data['type'] = $this->User_model->get_question_types($survey_id);
				$data['has_groups'] = $this->User_model->has_groups($survey_id);
				$data['categories'] = $this->User_model->get_categories($survey_id);
				$gate['body'] = $this->load->view('user/create_questions',$data, TRUE);
				$this->load->view('main', $gate);						
			}
			else{//you cannot add anymore because someone has already answered
				$id = $data['id'];
				echo "<script>javascript:alert('You cannot add a question.'); window.location = 'http://localhost/pollwatcher/index.php/user/view_certain_survey/$id/$survey_id'</script>";
			}			
			

		}

		/*
			Allows the user to create a survey.
		*/
		function create_survey($id){
			$data = array();
			$data['id'] = $this->session->userdata('id');

			
			$data['year_cur'] = (int)date('Y');
			$data['month_cur'] = (int)date('m');
			$data['day_cur'] = (int)date('d');

			
			$data['templates'] = array();
			if ($handle = opendir('templates/notification')) {
				
				while (false !== ($file = readdir($handle))) {
					if (substr($file, -4) == '.txt') {
						$data['templates'][] = file_get_contents('templates/notification/'.$file);
					}
					
				}

				closedir($handle);
			}
			
			$gate['body'] = $this->load->view('user/create_survey',$data, TRUE);
//			redirect('user/view_certain_survey');
			$this->load->view('main', $gate);
		}

		/*
			allows the user to view a single survey and show a preview of the survey.
			Parameters:
				$id = the userid of the user so that we will know which surveys to access
				$survey_id = the id of the survey so that we will be able to know which survey to access.
		*/
		function view_certain_survey($id,$survey_id){ 

			$id_test = $this->session->userdata('id');
			$data['survey_id'] = $survey_id;
			//test if a subuser.
			$isSubuser = $this->User_model->isSubuser($id_test,$survey_id);
			$data['isSubuser'] = $isSubuser;


			if ($isSubuser){//case when you are a subuser
				$super_user_id =  $this->User_model->getSuperuserId($survey_id);
				
				$data['id'] = $super_user_id;
				
				//get the privileges of the subuser
				$data['privileges'] = $this->User_model->get_privileges($id_test,$super_user_id);
				
			}
			else{//case when you are a superuser. thus giving full privileges
				$data['id'] = $this->session->userdata('id');
			}
			$data['title'] = $this->User_model->get_survey_title($survey_id);
			$data['today'] = date('Y-m-d');
			$data['end_date'] = $this->User_model->get_end_date($survey_id);
			
			$temp = $this->Respondent->fetchQuestionsViaId($survey_id);
			$data['questions'] = $temp['questions'];
			$data['categories'] = $this->Respondent->getCategories($survey_id);
			
			$gate['body'] = $this->load->view('user/view_survey',$data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
		 * This function basically invites respodent.
		 * The conditional statement inside is the one responsible for user templates. 
		 */
		function invite_resp($id,$survey_id){
			$data = array();
			$data['survey_id'] = $survey_id;
			$data['id'] = $this->session->userdata('id');
			$data['templates'] = array();
			if ($handle = opendir('templates/invitation')) {
				
				while (false !== ($file = readdir($handle))) {
					if (substr($file, -4) == '.txt') {
						$data['templates'][] = file_get_contents('templates/invitation/'.$file);
					}
					
				}

				closedir($handle);
			}
			$gate['body'] = $this->load->view('user/invite_resp',$data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
		 * This function basically lets a user add a subuser.
		 * This is the one responsible for validating the form posted.
		 */
		function addsubuser(){
			$rules = array();
			$rules['subuser'] = "required|valid_email";
			$rules['invitation_message'] = "required";

			$this->validation->set_rules($rules);
			$this->validation->set_error_delimiters('<div id="error">', '</div>');

			if ($this->validation->run()==TRUE){
				if($this->User_model->alreadyASubuser($this->session->userdata('id'), $this->input->post('subuser'))){
					$data['error'] = '<div id = error> The subuser you entered is already a subuser. </div>';
				} else {
					$set['superuser'] = $this->session->userdata('id');
					$set['subuser'] = $this->input->post('subuser');
					$set['invitation_message'] = $this->input->post('invitation_message');
					$set['edit_questions'] = $this->input->post('edit_questions');
					$set['invite_respondents'] = $this->input->post('invite_respondents');
					$set['view_reports'] = $this->input->post('view_reports');
					$set['end_survey'] = $this->input->post('end_survey');
				
					$this->User_model->insertSubUsers($set);
					$config = array(
					  'protocol' => 'smtp',
					  'smtp_host' => 'ssl://smtp.googlemail.com',
					  'smtp_port' => 465,
					  'smtp_user' => 'pollwatcher.god@gmail.com',
					  'smtp_pass' => 'ichigokurakurasakiU',
					);
					$this->load->library('email', $config);
					$this->email->set_newline("\r\n");

					$this->email->from('pollwatcher.god@gmail.com', 'PollWatcher');
					$this->email->to($this->input->post('subuser'));

						if($this->User_model->alreadyAMember($this->input->post('subuser'))){
							$set['member'] = TRUE;
							$this->email->subject('You have been invited as a subuser!');
						} else {
							$this->email->subject('You are invited to join PollWatcher!');
							$set['member'] = FALSE;
						}
						
						$this->email->message($this->load->view('subuser', $set, TRUE));
					if (!$this->email->send())
					  show_error($this->email->print_debugger());
				
					$this->session->set_flashdata('message', 'Please check your e-mail to confirm your registration.');
				}
				redirect('user/permissions');
			}
		}

		/*
			After a survey is created. It should be inserted to the database.
		*/
		function insert_survey_todb(){
			$survey_name = $_POST['survey_name'];
			$description = $_POST['description'];
			$begin_month = $_POST['month'];
			$begin_day = $_POST['day'];
			$begin_year = $_POST['year'];
			$end_month = $_POST['end_month'];
			$end_day = $_POST['end_day'];
			$end_year = $_POST['end_year'];
			$id = $_POST['id'];
			$sched =$_POST['sched'];
			$notif_body = $_POST['notification_message'];
			//actual insertion of the data about the survey.
			$survey_id =  $this->User_model->insert_survey($survey_name,$description,$begin_month,$begin_day,$begin_year,$end_month,$end_day,$end_year,$id,$sched, $notif_body);
			
			$firstname = 0;
			$middlename = 0;
			$lastname = 0;
			$gender = 0;
			$birthday = 0;
			$location = 0;
			$key = 1;
			
			//check for categories
			if (array_key_exists("checker",$_POST)){
				while(array_key_exists("group".$key,$_POST)){
					$this->User_model->insert_category($id,$survey_id,$_POST["group".$key]);
					$key++;				

				}			
			}
			else{
			}
			
			if (!array_key_exists('required',$_POST)){
				//$required = $_POST['required'];
			}
			else{
				
				$required_fields = $_POST['required'];
				$limit = count($required_fields);
				//gets the required fields
				for($i= 0 ; $i<$limit; $i++){
					if ($required_fields[$i] == "firstname"){
						$firstname = 1;
					}
					else if ($required_fields[$i] == "middlename"){
						$middlename = 1;
					}
					else if ($required_fields[$i] == "lastname"){
						$lastname = 1;
					}
					else if ($required_fields[$i] == "gender"){
						$gender = 1;
					}
					else if ($required_fields[$i] == "location"){
						$location = 1;
					}
					else if ($required_fields[$i] == "birthday"){
						$birthday = 1;
					}
					
				}
					
			}
			//insertion of the required fields to the database
			$this->User_model->insert_required($survey_id,$firstname,$middlename,$lastname,$gender,$birthday,$location);

			$data['id'] = $id;
			$surveys = $this->User_model->get_my_surveys($id); //user id to
			$data['surveys'] = $surveys;


			
			$gate['body'] = $this->load->view('user/survey_options',$data, TRUE);
			$this->load->view('main',$gate);
			redirect('user/add_question/'.$survey_id."/".$id);
		}

		/*
			Shows all the questions so that the user can choose which one to delete.
			Parameter:
				$survey_id - to know which questions of a survey you must access.
		*/
		function delete_questions($survey_id){
			$data = array();
			$data['survey_id'] = $survey_id;
			$data['id'] = $this->session->userdata('id');
			//count the number of respondents who have answered your survey
			$answer = $this->User_model->count_answer_check($survey_id);
			if ($answer == 0){//if no one has answered your survey, you can still delte a question.
				$questions = $this->User_model->get_questions($survey_id);
				$data['questions'] = $questions;
							
				$gate['body'] = $this->load->view('user/delete_questions',$data, TRUE);			
			}
			else{//if at least one has answered, you are not allowed anymore
				$id = $data['id'];
				echo "<script>javascript:alert('You cannot delete a question.'); window.location = 'http://localhost/pollwatcher/index.php/user/view_certain_survey/$id/$survey_id'</script>";
			}

			$this->load->view('main', $gate);
		}

		/*
			permanently deletes a survey from the database.
			Parameter:
				$survey_id = the id of the survey that you want to delete.
		*/
		function actual_deletion($survey_id){
			$id_test = $this->session->userdata('id');
			$data['survey_id'] = $survey_id;
			$data['title'] = $this->User_model->get_survey_title($survey_id);
			$data['id'] = $id_test;
			$data['today'] = date('Y-m-d');
			$data['end_date'] = $this->User_model->get_end_date($survey_id);
			$toDelete = $_POST['choice'];
			$this->User_model->delete_from_db($toDelete,$survey_id);
			
			
			//test if the one who is accessing the survey is a subuser or not
			$isSubuser = $this->User_model->isSubuser($id_test,$survey_id);
			
			$data['isSubuser'] = $isSubuser;
			
			if ($isSubuser){//if a subuser, get privileges to know what things he can do.
				$super_user_id =  $this->User_model->getSuperuserId($survey_id);
				
				$data['id'] = $super_user_id;
				
				$data['privileges'] = $this->User_model->get_privileges($id_test,$super_user_id);
				
			}
			else{// otherwise, allow full privilege over the survey.
				$data['id'] = $this->session->userdata('id');
			}

			
			
			$questions = $this->User_model->get_questions($survey_id);
			$i = 1;
			foreach($questions->result() as $row)
			{
				//updates the numbering of the questions so that they are still ordered from 1 to n
				$this->User_model->update_numbering($row->question_number, $i, $survey_id);
				$i++;
			}
			$temp = $this->Respondent->fetchQuestionsViaId($survey_id);
			$data['questions'] = $temp['questions'];
			
			//get the categories used by this survey.
			$data['categories'] = $this->Respondent->getCategories($survey_id);
			$gate['body'] = $this->load->view('user/view_survey',$data, TRUE);
			$this->load->view('main', $gate);			
		}
		
		
		/*
			Shows all the questions in a certain survey that was made by the user. The user id is tracked
			via the session variables.
			Parameters: 
				$survey_id - tells which survey to access and where to get the questions to update.
		*/
		function update_questions($survey_id){
			$data = array();
			$data['survey_id'] = $survey_id;
			$data['id'] = $this->session->userdata('id');
			//count the number of respondents who have answered your survey.
			$answers = $this->User_model->count_answer_check($survey_id);
			if($answers == 0){//if no one has answered, you can still update a question.
				$questions = $this->User_model->get_questions($survey_id);
				$data['questions'] = $questions;
				
				$gate['body'] = $this->load->view('user/update_questions',$data, TRUE);				
			}
			else{//otherwise, do not allow
				$id = $data['id'];

				echo "<script>javascript:alert('You cannot edit a question.'); window.location = 'http://localhost/pollwatcher/index.php/user/view_certain_survey/$id/$survey_id'</script>";
			}

			$this->load->view('main', $gate);
		}

		/*
			Shows the form where you can edit the values that you have entered before in a certain question.
			Parameters:
				$survey_id - the survey where the question belongs. 
		*/
		function questions_to_update($survey_id)
		{
			$data['id'] = $this->session->userdata('id');
			$data['survey_id'] = $survey_id;
			$toUpdate = $_POST['choice'];
			
			$N = count($toUpdate);
			for($i = 0; $i < $N; $i++)
			{
				$q_num = $toUpdate[$i];
				$questions[$i] = $this->User_model->get_a_question($survey_id, $q_num);
				$choices[$i] = $this->User_model->get_choices($survey_id,$q_num);
			}
			$data['questions'] = $questions;
			$data['choices'] = $choices;
			$data['type'] = $this->User_model->get_question_types($survey_id);
			
			$sql = "SELECT count(*) as counted FROM choices
					WHERE question_number = $q_num
					AND survey_number =$survey_id";
			$query = $this->db->query($sql);
			$count = $query->row()->counted;
			//echo $count;
			$data['count'] =  $count;
			//used to know if the survey has a question group
			$data['has_groups'] = $this->User_model->has_groups($survey_id);
			$data['categories'] = $this->User_model->get_categories($survey_id);
			
			$gate['body'] = $this->load->view('user/edit_questions',$data, TRUE);
			$this->load->view('main', $gate);
			
		}

		/*
			The part where the questions are updated to the database.
			Parameters:
				$survey_id - the id of the survey where the question belongs.
		*/
		function actual_question_update($survey_id)
		{
			$user_id = $this->session->userdata('id');
			$question_count = $_POST['num_questions'];
			
			//get the number of checkbox to check. if a question is of different type, this is zero.
			if (array_key_exists("choice_limit",$_POST)){
				$choice_limit = $_POST['choice_limit'];
			}
			else{
				$choice_limit = 0;
			}
			
			//test if a survey has categories in it
			if(array_key_exists("category",$_POST)){
				
				$category_name = $_POST['category'];
				//echo $category_name;
			}
			else{
				$category_name = "";
			}
			$null = $_POST['null'];//choice_limit,category,null
			for($i = 0; $i < $question_count; $i++)
			{
				$question_number = $_POST['question_id'.$i];
				$body = $_POST['question'.$i];
				$type = $_POST['type'.$i];				
				
				
				$text_label = $_POST['text_label'.$i];
				
				if(!isset($_POST['with_text'.$i]))
				{
					$with_text = 0;
				}else {
					$with_text = $_POST['with_text'.$i];
				}
				
				if($type == "text")
				{
					$required = $_POST['required'.$i];
				}else {
					$required = 0;
				}
				//actual update on the survey.
				$this->User_model->update_question($survey_id, $question_number, $body, $type, $with_text, $text_label, $required,$choice_limit,$null,$category_name);
				$limit =  $_POST['choice_value'.$i];
				
				for($j = 1; $j <=$limit; $j++){
					$key = "choice".$i.":".$j;
					$choice = $_POST[$key];
					$new['survey_number'] = $survey_id;
					$new['question_number'] = $question_number;
					$new['choice_number'] = $j;
					$new['body'] = $choice;
					
					$this->User_model->insert_choice($new);
				}
				
				//echo $survey_id . " ". $question_number . " ". $body . $type. $with_text." ". $text_label. " " .$required ."<br>";
			}
			$this->view_certain_survey($user_id, $survey_id);
		}

		/*
			Ends a survey so that no one can answer it anymore.
			Sets the end date of the survey to the current date.
		*/
		function end_survey($id,$survey_id){
			$data = array();
			$data['survey_id'] = $survey_id;
			$data['id'] = $this->session->userdata('id');
			$this->User_model->end_survey_now($survey_id);
			$gate['body'] = $this->load->view('user/end_survey',$data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
			Permanently deletes a survey from the database.
		*/
		function actual_survey_delete(){
			$toDelete = $_POST['survey'];
			$this->User_model->delete_survey_from_db($toDelete);
			redirect('user/delete_survey');
		}
		
		/*
			Edits the settings of the survey.
		*/
		function actual_survey_edit(){
			
			$toEdit = $_POST['survey']; //survey_id
			$survey = "SELECT title,description,date_created,begin_date,end_date,notif_sched,notif_body FROM survey
						WHERE survey_id= '$toEdit'";
			$req = "SELECT * FROM required_fields WHERE survey_id ='$toEdit'";
			$query_survey =  $this->db->query($survey);
			$query_req = $this->db->query($req);
			//$data['answers'] = $this->User_model->count_answer($toEdit);
			
			$data['has_groups'] = $this->User_model->has_groups($toEdit);
			$categories = $this->User_model->get_categories($toEdit);
			$data['categories'] = $categories;
			$i = 0;
			foreach($categories->result() as $category){
				$i++;
			}
			$data['count'] = $i;
			//echo $i;
			$answers = $this->User_model->count_answer_check($toEdit);
			$data['answers'] = $answers;
			$data['req'] = $query_req;
			$data['survey'] = $query_survey;
			$data['survey_id'] = $toEdit;
			$data['id'] = $this->session->userdata('id');
			$data['templates'] = array();
			if ($handle = opendir('templates/notification')) {
				
				while (false !== ($file = readdir($handle))) {
					if (substr($file, -4) == '.txt') {
						$data['templates'][] = file_get_contents('templates/notification/'.$file);
					}
					
				}

				closedir($handle);
			}
			$gate['body'] = $this->load->view('user/actual_edit_survey',$data, TRUE);
			

			$this->load->view('main',$gate);
			
		}

		/*
			Shows the surveys created by the user and allows them which one to delete.
		*/
		function delete_survey(){
			$data['id'] = $this->session->userdata('id');
			$surveys = $this->User_model->get_my_surveys($data['id']); //user id to
			$data['surveys'] = $surveys;
			$gate['body'] = $this->load->view('user/delete_survey',$data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
		 * This function basically just shows what's in the database and loads in the views.
		 */
		function permissions(){//views the settings ad where you can edit it
			$data['id'] = $this->session->userdata('id');
			$data['subuser'] = $this->User_model->getSubUser($data['id']); //user id to
			$data['templates'] = array();
			if ($handle = opendir('templates/permission')) {
				
				while (false !== ($file = readdir($handle))) {
					if (substr($file, -4) == '.txt') {
						$data['templates'][] = file_get_contents('templates/permission/'.$file);
					}
					
				}

				closedir($handle);
			}
			$gate['body'] = $this->load->view('user/permissions',$data, TRUE);
			$this->load->view('main',$gate);
		}

		/*
		 * This function is basically responsible for editing privileges for its subusers. 
		 */
		function edit_privileges(){
			$data['id'] = $this->session->userdata('id');
			$data['subuser'] = $this->User_model->getSubUser($data['id']);
			$i=1;
			foreach($data['subuser']->result() AS $list){				
				$list->edit_questions = $this->input->post('edit_questions'.$i);
				//echo "woot";
				//echo $this->input->post('edit_questions'."2");
				$list->invite_respondents = $this->input->post('invite_respondents'.$i);
				$list->view_reports = $this->input->post('view_reports'.$i);
				$list->end_survey = $this->input->post('end_survey'.$i);
				$this->User_model->update_privileges($list, $list->subuser);
				//echo $i;
				$i++;
			}
			redirect('user/permissions');
		}

		/*
		 * This is for subusers to edit his/her own personal profile.
		 */
		function edit_profile(){
			$email = $this->User_model->get_email($this->session->userdata('id'));
			$pic = $this->session->userdata('id').$email;
			$filename = "uploads/".$pic.".jpg";
			
			//echo $filename;
			$config['upload_path'] = './uploads/';
			$config['allowed_types'] = 'gif|jpg|png';
			$config['max_size']	= '150';
			$config['file_name'] = $pic.".jpg";
			

			$config['max_width']  = '1024';
			$config['max_height']  = '768';

			$this->load->library('upload', $config);
			if ( ! $this->upload->do_upload())
			{
				$error = array('error' => $this->upload->display_errors());

				//$this->load->view('upload_form', $error);
			}
			else
			{
				
				$data = array('upload_data' => $this->upload->data());

				//$this->load->view('upload_success', $data);
			}
			if (file_exists($filename) AND file_exists("uploads/".$this->session->userdata('id').$email."1".".jpg")){
				//echo "wooot";
				unlink($filename);
				rename("uploads/".$pic."1".".jpg",$filename);	
			}
			else{
				//echo "wttff";
			}	

			
			$data['id'] = $this->session->userdata('id');	
			$data['email'] = $this->session->userdata('email');
			$reguser = $this->Profile->select($data['id']);

			$rules['firstname'] = "required";
			$rules['lastname'] = "required";
			$rules['gender'] = "required";
			$rules['month'] = "required";
			$rules['day'] = "required";
			$rules['year'] = "required";

			$this->validation->set_rules($rules);
			$this->validation->set_error_delimiters('<div id="error">', '</div>');

			if ($this->validation->run()==TRUE){
			//echo "PASS";
				$reguser['firstname'] = $this->input->post('firstname');
				$reguser['lastname'] = $this->input->post('lastname');
				$reguser['middlename']= $this->input->post('middlename');
				$reguser['gender']= $this->input->post('gender');
				$reguser['month'] = $this->input->post('month');
				$reguser['day'] = $this->input->post('day');
				$reguser['year'] = $this->input->post('year');
				

				$month = $this->input->post('month'); 
				$day = $this->input->post('day');
				$year = $this->input->post('year');
				$months = array('jan'=>1,'feb'=>2,'mar'=>3,'april'=>4,'may'=>5,'june'=>6,'july'=>7,'august'=>8,'sept'=>9,'oct'=>10,'nov'=>11,'dec'=>12); 
				$reguser['birthday']= date("Y-m-d", mktime(0,0,0,$months[$month],$day,$year));
				$reguser['profile_pic'] = $pic.".jpg";
				$this->Profile->update($reguser, $this->session->userdata('id'));

				redirect('user/edit_profile');
			} 

			$user = $this->Login->refresh('user', $data['id']);
				$sessionData = array(
					'firstname' => $user['firstname'],
					'lastname' => $user['lastname'],
					'email' => $user['email'],
					'id' => $user['user_id'],
					'logged_in' => TRUE,
					'status' => $user['status'],
				);
			$this->session->set_userdata($sessionData);
			$this->session->set_flashdata('message', 'Please login again.');

			$data['reguser'] = $reguser;
			//$this->load->view('upload_form', array('error' => ' ' ));//papalitan pa haha
			$gate['body'] = $this->load->view('user/edit_profile', $data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
		 * As the function says, this is responsible for validating the changes in password a user makes.
		 */
		function change_password(){
			$data['id'] = $this->session->userdata('id');	
			$data['email'] = $this->session->userdata('email');
			$reguser = $this->Profile->select($data['id']);

			$rules['new_password'] = "trim|required|min_length[6]|alpha_dash";
			$rules['conf_new_password'] = "matches[new_password]";

			$this->validation->set_rules($rules);
			$this->validation->set_error_delimiters('<div id="error">', '</div>');

			if ($this->validation->run()==TRUE){
				//echo "PASS";
				$salt = random_string('alnum', 40);
				$reguser['salt'] = $salt;
				$password = $this->input->post('new_password');
				$hash = sha1($salt.$password);
				$reguser['password'] = $hash;
				$this->Profile->update($reguser, $this->session->userdata('id'));

				$config = Array(
				  'protocol' => 'smtp',
				  'smtp_host' => 'ssl://smtp.googlemail.com',
				  'smtp_port' => 465,
				  'smtp_user' => 'pollwatcher.god@gmail.com',
				  'smtp_pass' => 'ichigokurakurasakiU',
				);
				$this->load->library('email', $config);
				$this->email->set_newline("\r\n");

				$this->email->from('pollwatcher.god@gmail.com', 'PollWatcher');
				$this->email->to($this->session->userdata('email'));
				$fname = $this->session->userdata('firstname');
				$lname = $this->session->userdata('lastname');
		
				$this->email->subject("Change of Password!");
				$this->email->message("Hello $fname $lname \nThis is to inform you that you changed your password.");

				if (!$this->email->send())
				  show_error($this->email->print_debugger());
				$this->session->sess_destroy();
				redirect('gate');
			}
			
			$data['reguser'] = $reguser;
			$gate['body'] = $this->load->view('user/edit_profile', $data, TRUE);
			$this->load->view('main', $gate);
		}

		/*
		function insert_survey_todb(){
		}*/
		function update_survey_todb(){
			$survey_id = $_POST['survey_id'];
			$title = $_POST['survey_name'];
			$description = $_POST['description'];
			$begin_month = $_POST['month'];
			$begin_day = $_POST['day'];
			$begin_year = $_POST['year'];
			$end_month = $_POST['end_month'];
			$end_day = $_POST['end_day'];
			$end_year = $_POST['end_year'];
			$sched = $_POST['sched'];
			$notif_body = $_POST['notification_message'];
			$has_groups = $this->User_model->has_groups($survey_id);
			if(array_key_exists('checker',$_POST)){
				if ($has_groups == false){ //remove previous questions
					$sql = "DELETE FROM categories
							WHERE survey_id = $survey_id";
					$sql2 = "DELETE FROM question
							WHERE survey_id = $survey_id";
					$this->db->query($sql);
					$this->db->query($sql2);					
				}
				if (array_key_exists('toDelete',$_POST)){
					$toDelete = $_POST['toDelete'];
				}
				else{
					$toDelete = array();
				}
				$categories = $this->User_model->get_categories($survey_id);
				$count = 0;
				foreach($categories->result() as $row){
					$count++;
				}
				$key = 1;
				
				$sql = "SELECT user_id FROM survey
						WHERE survey_id = $survey_id";
				$query = $this->db->query($sql);				
				$id = $query->row()->user_id;
	
				$sql2 = "SELECT category_name,category_id FROM categories
						WHERE survey_id = $survey_id";
				$query2 = $this->db->query($sql2);
				$cat_id_index = 0;
	
				while(array_key_exists("group".$key,$_POST)){
					if ($key > $count){ //may bago
						$this->User_model->insert_category($id,$survey_id,$_POST["group".$key]);
					}
					else{
						$category_name = $_POST["group".$key];
						//echo $category_name;
						$category_id = $query2->row($cat_id_index)->category_id;
						$old_cat_name = $query2->row($cat_id_index)->category_name;
						//echo $category_id;
						$this->User_model->update_category($category_id,$survey_id,$category_name,$old_cat_name);
						$cat_id_index++;
					}
					$key++;
				}
			}
			else{
				if($has_groups){
					$sql = "DELETE FROM categories
							WHERE survey_id = $survey_id";
					$sql2 = "DELETE FROM question
							WHERE survey_id = $survey_id";
					$this->db->query($sql);
					$this->db->query($sql2);					
				}
				else{ //dati ng walang group
				}

				$toDelete = array();
			}
			

			
			//if ()
			/*
			echo $title,"<br>";
			echo $description,"<br>";
			echo $begin_month,"<br>";
			echo $begin_day,"<br>";
			echo $begin_year,"<br>";
			echo $end_month,"<br>";
			echo $end_day,"<br>";
			echo $end_year,"<br>";
			*/
			
			if (array_key_exists('required',$_POST)){
				$required = $_POST['required'];
			}
			else{
				$required = null;
			}
			$this->User_model->update_survey($survey_id,$title,$description,$begin_year,$begin_month,$begin_day,$end_year,$end_month,$end_day,$sched,$required,$toDelete, $notif_body);
			redirect('user/view_survey');
		}
		
		function add_category($survey_id)
		{
			$data = array();
			$data['survey_id'] = $survey_id;
			$data['id'] = $this->session->userdata('id');
			$data['count'] = $this->User_model->getCategoryCount($survey_id);
			$gate['body'] = $this->load->view('user/add_category', $data, TRUE);
			$this->load->view('main', $gate);
			
			if($this->input->post("no_category") == TRUE)
			{
				redirect("/user/add_question/".$survey_id);
			}
			
			else if($this->input->post("no_category") == FALSE)
			{
				$data = array("survey_id" => $survey_id, "group_name" => $this->input->post("category"));
				$this->User_model->insertCategory($data);
			}
			
			else
			{
				
			}
		
		}

		/*
		 * This function basically shows a user his/her superuser/s.
		 */
		function manage_survey(){
			$data['id'] = $this->session->userdata('id');
			$useremail = $this->session->userdata('email');		
			$data['email'] = $useremail;
			$data['superuser'] = $this->User_model->getSuperUser($useremail); //user id to
			$gate['body'] = $this->load->view('user/manage_survey',$data, TRUE);
			$this->load->view('main', $gate);
		}
	}
?>
